package com.sap.businessone.xapp;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.Test;

import com.sap.businessone.web.util.Base64Util;
import com.sap.businessone.web.util.HttpBot;
import com.sap.businessone.web.util.HttpResult;

public class LoginTest {

    private static final Logger log = LogManager.getLogger(LoginTest.class.getName());

    @Test
    public void requestBot() {
        String[] list = new String[] { "http://www.bing.com", "https://www.bing.com", "http://www.baidu.com", "http://unknown.site", "http://www.baidu.com/404" };

        for (String uri : list) {
            HttpResult rs = HttpBot.get(uri, null, null);
            log.info("[GET] " + uri);
            log.info(rs);
        }
    }

    @Test
    public void postBot() throws Exception {
        String uri = "http://msdn.microsoft.com/en-us/subscriptions/json/GetFileSearchResult";
        String body = "{\"Languages\":\"en\",\"Architectures\":\"arm\",\"ProductFamilyIds\":\"\",\"FileExtensions\":\"\",\"MyProducts\":false,\"ProductFamilyId\":0,\"SearchTerm\":\"\",\"Brand\":\"MSDN\",\"PageIndex\":0,\"PageSize\":10,\"FileId\":58466}";

        String s1 = URLEncoder.encode("some raw text", Consts.UTF_8.name());
        String s2 = URLDecoder.decode("some encoded text", Consts.UTF_8.name());

        HttpResult rs = HttpBot.post(uri, body, ContentType.APPLICATION_JSON, null, null);
        log.info("[POST] " + uri);
        log.info(rs);

        if (rs.getStatus() != HttpStatus.SC_OK) {
            log.error(rs.getBody());
        }
    }

    @Test
    public void auth() {
        String uri = "http://msdn.microsoft.com";

        Map<String, String> headers = new LinkedHashMap<String, String>();
        String user = "SYSTEM", pwd = "manager";
        String code = Base64Util.encode(("Basic " + user + ":" + pwd).getBytes());
        headers.put("auth", code);

        HttpResult rs = HttpBot.get(uri, headers, null);
        log.info("[GET] " + uri);
        log.info(rs);
    }
}
